package com.ztesoft.zsmart.zcm.dialing.util;

import com.google.common.base.Strings;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @Author xuduan
 * @Date 2021/2/25 0025 15:26
 */
public class JsonParser {

    private List<String> pathList;
    private String json;

    public JsonParser(String json) throws JSONException {
        this.json = json;
        this.pathList = new ArrayList<String>();
        if (!Strings.isNullOrEmpty(json)) {
            setJsonPaths(json);
        }
        else {
            pathList = new ArrayList<>();
        }
    }

    public List<String> getPathList() {
        return this.pathList;
    }

    private void setJsonPaths(String json) throws JSONException {
        this.pathList = new ArrayList<String>();
        JSONObject object = new JSONObject(json);
        String jsonPath = "$";
        if (json != JSONObject.NULL) {
            readObject(object, jsonPath);
        }
    }

    private void readObject(JSONObject object, String jsonPath) throws JSONException {
        Iterator<String> keysItr = object.keys();
        String parentPath = jsonPath;
        while (keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);
            jsonPath = parentPath + "." + key;
            if (value instanceof JSONArray) {
                readArray((JSONArray) value, jsonPath);
            }
            else if (value instanceof JSONObject) {
                readObject((JSONObject) value, jsonPath);
            }
            else {
                this.pathList.add(jsonPath);
            }
        }
    }

    private void readArray(JSONArray array, String jsonPath) throws JSONException {
        String parentPath = jsonPath;
        for (int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            jsonPath = parentPath + "[" + i + "]";
            if (value instanceof JSONArray) {
                readArray((JSONArray) value, jsonPath);
            }
            else if (value instanceof JSONObject) {
                readObject((JSONObject) value, jsonPath);
            }
            else {
                this.pathList.add(jsonPath);
            }
        }
    }

    public void setPathList(List<String> pathList) {
        this.pathList = pathList;
    }

    public String getJson() {
        return json;
    }

    public void setJson(String json) {
        this.json = json;
    }
}
